package net.sahv.bdyz.api;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.PatternFilter;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.service.PatternFilterService;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.util.ImagePHash;
import net.sahv.bdyz.util.LoadCfgUtil;
import net.sahv.bdyz.util.PageInfo;

@Controller("apiPatternFilterController")
@RequestMapping("api/patternfilter/")
public class PatternFilterController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private PatternFilterService patternFilterService;
	@Autowired
	private PatternService patternService;
	@Autowired 
	CookieLocaleResolver resolver;
	
	/**
	 * 以图搜图  王聪朝  2016年9月6日14:13:37
	 * @param request
	 * @param response
	 * @param model
	 * @param canshu
	 * @param page
	 * @return
	 * @throws Exception 
	 */		
	@RequestMapping(value = "flowertypecatalog{page}")
	public String dopositionByImg(HttpServletRequest request,HttpServletResponse response,Model model,String filePath,String page,String key) throws Exception {
		key = new String(key.getBytes("ISO-8859-1"),"utf-8");
		Object languageObj=request.getSession().getAttribute("language");
		String yuyan = "";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA);
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH);
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA);
				}
			}
		}else{
			yuyan="ch";
		}
		model.addAttribute("yuyan", yuyan);
		Member member = memberService.getCurrent();//获取当前登录人信息
		List<Map<String, Object>> zong = new ArrayList<>();
		List<PatternFilter> list = patternFilterService.selectAllBypid(0,yuyan);
		for (PatternFilter item : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<PatternFilter> zilist = patternFilterService.selectAllBypid(item.getPtId(),yuyan);
			map.put("fuji", item);
			map.put("zi", zilist);
			zong.add(map);
		}
		model.addAttribute("shuju", zong);
		model.addAttribute("canshu", "all");
		// 查询
		PageInfo pageInfo = new PageInfo();
		if(page==null||page.equals("")){
			page="1";
		}
		pageInfo.setPage(Integer.valueOf(page));
		pageInfo.setPageSize(20);
		ImagePHash push = new ImagePHash();     
     	String where="1=1";
		if(filePath!=null&&!filePath.equals(""))
     	{
			String realPath = request.getServletContext().getRealPath(filePath);
			String imgSerial=push.getHash(new FileInputStream(new File(realPath)));     		     	       		
 	     	//添加搜索图片条件
	        where+=" AND P_BUYOUT_STATE=0 and P_VIP!='4' and getCounter(P_MESSAGE1,'"+imgSerial+"')<20 and P_MESSAGE1!='' AND !isnull(P_MESSAGE1)";
     	}
		else
     	{
			if (key != null && !key.equals("")) {
    			if (key.contains("'")) {
    				key = key.replaceAll("'", "''");
				}
				// 根据key查询所有相关标签
				/*
				 * List<PatternFilter> pfList = patternFilterService
				 * .selectByName(" (PT_NAME like '%" + key +
				 * "%' or PT_NAME_EN like '%" + key + "%')"); String pfIds = "";
				 * if (pfList != null && pfList.size() > 0) { for (PatternFilter
				 * pf : pfList) { pfIds += " find_in_set('" + pf.getPtId() +
				 * "', TIAOJIAN) or"; } } if (pfIds != "") { pfIds =
				 * pfIds.substring(0, pfIds.length() - 2); where += " and (" +
				 * pfIds + ")"; }
				 */
				where += " AND P_BUYOUT_STATE=0 and P_VIP!='4' and  (P_NO  like '" + "%" + key
						+ "%' or P_MESSAGE2 like '%" + key + "%') ";
    		} 	     		
     	}
		List<Map<String, Object>> pattern = patternService.findAllByImg(pageInfo, "all", " ORDER BY P_ID DESC ",member,where);
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));
		model.addAttribute("pattern", pattern);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("member", member);
		model.addAttribute("filePath", filePath);
		model.addAttribute("key", key);
		return "phone/pattern/pattern";
	}
	
	 /**
     * 将byte数组转换成InputStream
     * @param in
     * @return 王聪朝2016年8月16日10:23:20
     * @throws Exception
     */
    public static InputStream byteTOInputStream(byte[] in) throws Exception{         
        ByteArrayInputStream is = new ByteArrayInputStream(in);
        return is;
    }
	
	




	
	
	
	
}
